
'''
    目的:
        This is only for csv format check.
        Stop check when find any format error and return error message.
    
    使用说明:
        导入csvft.py, 调用csvft(path)函数, path为csv路径.
        pass返回''
        格式错误返回错误信息

    功能:
        检查头字段, 包括宽度、元素个数, 关键字(每列头名不能变更)
        测试项目的名称不能重复
        每行字段不能少, 14列
        不能有空行
        配置文件后缀必须是csv
'''

import csv
import os

csvFilePath = 'Process.csv'
seperater = ','

__version__ = '0.0.1'
__author__  = 'GTK RD HWTE'

# 统计元素个数，包含空字符
def column_count(lst):
    count = 0
    for value in lst:
        count = count + 1
    
    return count

header_names = ['TestName', 'TestActions', 'Disable', 'Input', 'Output', 'Timeout', 'Retries', 'AdditionalParameters', 'ExitEarly', 'SetPoison', 'Commands', 'FA', 'Condition', 'Notes']
column_numbers = column_count(header_names)
datas = []

def csvft(path):

    assert(path)

    #   检查原文件是否存
    if not os.path.exists(path):
        print('csv file path is not exist')
        return 'can not detect csv file for checking...'

    #   文件类型检查, 非csv文件报错
    csvFile = path.upper()
    isCsv = csvFile.endswith('CSV')
    if not isCsv:
        return 'It is not csv file'

    csv_reader = ''
    item_names = []

    #   
    with open(path, 'r') as file:
        csv_reader = csv.reader(file)

        for line in csv_reader:
            content_number = column_count(line)
            datas.append(line)

            #   有效列检查
            if content_number != column_numbers :
                return 'csv file column format error'
            
            #   测试名称保存
            if len(line[0]) > 0:
                item_names.append(line[0])
        

        #   测试项目名称重复检查, 这个检测方法不够严谨, 紧从数量上判断差别.
        first_length  = len(item_names)
        second_length = len(set(item_names))

        if first_length != second_length:
            return 'There are the same test item names in the list'
            
        heads = datas[0]

        # head info check
        for value in heads:
            if value not in header_names:
                return 'csv head info format error'
        
        for value in header_names:
            if value not in heads:
                return 'csv head info format error'

    return ''
    

if __name__ == '__main__':
    print(csvft(csvFilePath))